# -*- coding: utf-8 -*-
"""
@Time ： 2021/7/12 15:31
@Auth ： Mr. royalday 2487625775
@Company ：XXX
@Function ：请输入模块功能描述
"""
import json

from django.http import JsonResponse

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.views import APIView

from utils import encrypt
from web import models
from web.forms.account import LoginForm


def gettags(request):
    """获取接口分组信息"""
    data = [
        {"name": "用户管理"},
        {"name": "用例管理"}
    ]
    res = {"code": 200, "msg": "标签加载成功", "data": data}
    return JsonResponse(res)


class GetCase(APIView):
    @swagger_auto_schema(
        operation_description='在自动化平台修改一个用例的信息',
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['id'],
            properties={
                'id': openapi.Schema(type=openapi.TYPE_INTEGER, description='用例id'),
                'casename': openapi.Schema(type=openapi.TYPE_STRING, description='用例名'),
                'stepname': openapi.Schema(type=openapi.TYPE_STRING, description='步骤名'),
                'keywords': openapi.Schema(type=openapi.TYPE_STRING, description='关键字'),
                'params1': openapi.Schema(type=openapi.TYPE_STRING, description='参数1'),
                'params2': openapi.Schema(type=openapi.TYPE_STRING, description='参数2'),
            },
        ),
        # responses={210: openapi.Response('response description', UpdateCaseErrCode)},
        # tags=['用例管理', 'application/json', 'application/json;'],
        tags=['用例管理', 'application/json', 'application/json;'],
        operation_summary='修改用例',
    )
    def post(self, request):
        """
        登录平台，登录后sessionid会具备登录态
        """
        return JsonResponse({"code": 1000, "msg": '更新成功'})


class Login(APIView):
    @swagger_auto_schema(
        operation_description='登录',
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['username', 'password'],
            # required=['username', 'password', 'code'],
            properties={
                'username': openapi.Schema(type=openapi.TYPE_STRING, description='用户名', default='15879924717'),
                'password': openapi.Schema(type=openapi.TYPE_STRING, description='密码', default='123456'),
                # 'code': openapi.Schema(type=openapi.TYPE_STRING, description='图片验证码'),
            },
        ),
        # responses={210: openapi.Response('response description', UpdateCaseErrCode)},
        tags=['用户管理', 'application/json', 'application/json;'],
        operation_summary='用户登录',
    )
    # def post(self, request):
    #     """
    #     登录平台
    #     """
    #     data = json.loads(request.body)
    #     username = data.get('username', '')
    #     password = data.get('password', '')
    #     form = LoginForm(request, instance=data)
    #
    #     if form.is_valid():
    #         # user_object_by_mob = models.UserInfo.objects.filter(username=username, password=password).first()
    #         # 实现邮箱或者手机号码作为用户名登录
    #         from django.db.models import Q
    #         user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
    #             password=password).first()
    #         if user_object:
    #             # 用户名密码正确
    #             request.session['user_id'] = user_object.id
    #             request.session.set_expiry(60 * 60 * 24 * 14)  # 登录成功后重新设置session过期时间
    #             return JsonResponse({"code": 1000, "msg": '登录成功'})
    #         return JsonResponse({"code": 1002, "msg": '账号或密码错误'})
    #     return JsonResponse({"code": 1001, "msg": '登录失败'})
    def post(self, request):
        """
        登录平台
        """
        data = json.loads(request.body)
        username = data.get('username', '')
        password = data.get('password', '')
        password = encrypt.md5(password)
        # code = request.session.get('img_code')

        if not (username is '' or password is ''):
            # user_object_by_mob = models.UserInfo.objects.filter(username=username, password=password).first()
            # 实现邮箱或者手机号码作为用户名登录
            from django.db.models import Q
            user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
                password=password).first()
            if user_object:
                # 用户名密码正确
                request.session['user_id'] = user_object.id
                request.session.set_expiry(60 * 60 * 24 * 14)  # 登录成功后重新设置session过期时间
                return JsonResponse({"code": 1000, "msg": '登录成功'})
            return JsonResponse({"code": 1002, "msg": '账号或密码错误'})
        return JsonResponse({"code": 1001, "msg": '登录失败'})


class GetImgCode(APIView):
    @swagger_auto_schema(
        operation_description='获取图片验证码',
        manual_parameters=[

        ],
        # responses={210: openapi.Response('response description', UpdateCaseErrCode)},
        tags=['用户管理', 'application/json', 'application/json;'],
        operation_summary='获取图片验证码',
    )
    def get(self, request):
        """
        登录平台
        """
        from utils.img_code import check_code
        img_object, code = check_code()
        return JsonResponse({"code": 1000, "data": {'code': code}})
